#include "ClearAreaAction.hpp"

ClearAreaAction::ClearAreaAction(Map* map, sf::Rect<int> src, bool cut){
    if(cut){
        desc = "Cut (" + StringHelper::itos(src.left) + "," + StringHelper::itos(src.top) + ") " + StringHelper::itos(src.width) + "x" + StringHelper::itos(src.height);
    }else{
        desc = "Cleared (" + StringHelper::itos(src.left) + "," + StringHelper::itos(src.top) + ") " + StringHelper::itos(src.width) + "x" + StringHelper::itos(src.height);
    }

    target = map;
    source = src;
    //Generate list of tiles in selected area that will be cleared.
    for(int l = 0; l < LAYERS; l++){
        for(int r = 0; r < source.height; r++){
            for(int c = 0; c < source.width; c++){
                if(source.left + c >= 0 && source.left + c < map->width 
                        && source.top + r >= 0 && source.top + r < map->height){
                    int tile = source.left + c + (r + source.top)*target->width;
                    if(target->tiles[tile][l] != -1){
                        ClearTile clearedTile;
                        clearedTile.layer = l;
                        clearedTile.tile = tile;
                        clearedTile.value = target->tiles[tile][l];
                        clearedTiles.push_back(clearedTile);
                    }
                }
            }
        }
    }
    perform();
}

void ClearAreaAction::perform(){
    //Clear tiles that need clearing.
    for(int l = 0; l < LAYERS; l++){
        for(int r = 0; r < source.height; r++){
            for(int c = 0; c < source.width; c++){
                if(source.left + c >= 0 && source.left + c < target->width 
                        && source.top + r >= 0 && source.top + r < target->height){
                    int tile = source.left + c + (r + source.top)*target->width;
                    target->tiles[tile][l] = NO_SPRITE;
                }
            }
        }
    }

}

void ClearAreaAction::undo(){
    //Return all cleared tiles to their original values.
    for(int i = 0; i < clearedTiles.size(); i++){
        target->tiles[clearedTiles.at(i).tile][clearedTiles.at(i).layer] = clearedTiles.at(i).value;
    }
}